import os
from datetime import datetime, timedelta

##os.system("start https://www.lanqiao.cn/problems/19730/learning/")

t = int(input())

beginTime = datetime(year = 1970, month = 1, day = 1, hour = 0, minute = 0, second = 0)

while t != 0:
    t -= 1
    
    a, b, x = list(input().split())

    x = int(x)

    yy, mm, dd = map(int, a.split('-'))
    HH, MM, SS = map(int, b.split(':'))

    endTime = datetime(yy, mm, dd, HH, MM, SS)

    deltaTime = endTime - beginTime

    deltaMinutes = deltaTime.days * 24 * 60 + deltaTime.seconds // 60;

    endTime -= timedelta(minutes = deltaMinutes % x, seconds = deltaTime.seconds % 60)
    print(endTime)

    
